package com.choker.mall.controller;

import com.choker.mall.entity.UserMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by Lychee on 2018/3/8 20:28.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */

@Controller
public class UploadFileController {

    /**
     * MultipartFile 是一个接口 他继承 Springmvc 定义的InputStreamSource 接口  他是一个流
     *
     * @param request
     * @param file
     */
    @RequestMapping(value = "/uploadType1", method = RequestMethod.POST)
    public void uploadFileType1(HttpServletRequest request,
                                @RequestParam("fileKey") MultipartFile file) {
        if (!file.isEmpty()) {
            //获得这个ServletRequest上一次的servlet上下文分发.getRealPath得到真正的路径对应于给定的虚拟路径。
            String path = request.getServletContext().getRealPath("/images/");

            //返回 远程传输的文件的文件名
            String fileName = file.getOriginalFilename();

            //根据路径创建文件
            File filePath = new File(path, fileName);

            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }

            try {
                //将远程上传的文件  转移到自定义的文件中
                file.transferTo(new File(path + File.separator + fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @RequestMapping(value = "/uploadType2", method = RequestMethod.POST)
    public void uploadFileType2(HttpServletRequest request, @ModelAttribute UserMessage userMessage, Model model) {
        if (!userMessage.getImage().isEmpty()) {
            String path = request.getServletContext().getRealPath("/images/");
            String fileName = userMessage.getImage().getOriginalFilename();
            File filePath = new File(path, fileName);
            if (!filePath.getParentFile().exists()) {
                boolean mkdirsOk = filePath.getParentFile().mkdirs();
            }
            try {
                userMessage.getImage().transferTo(new File(path + File.separator + fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
